# coding: utf-8

import datetime
import time
import requests

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text, select

# 开发使用URl
BASE_UPLOAD_AUDIO_URL = 'http://127.0.0.1:5000/outbound/ccx_audio/upload/{mobile}?record_datetime={record_datetime}'

# 线上使用URL
#BASE_UPLOAD_AUDIO_URL = 'http://opc.wanpinghui.com/outbound/ccx_audio/upload/{mobile}?record_datetime={record_datetime}'

DB_USER = 'cc'
DB_PWD = 'cc'
DB_HOST = '192.168.1.208:1521'
DB_NAME = 'orcl'
cc_engine = create_engine(
    'oracle+cx_oracle://%s:%s@%s/%s?charset=utf8' % (
        DB_USER, DB_PWD, DB_HOST, DB_NAME
    )
)

cc_conn = cc_engine.connect()

invalid_mobiles = ['400000000', '18900000000', '4009980215']

sql = text("""
select
    filename, location, callid, caller, dgentime, length
from
    ky.T_REC_STORE
where
    itenantid=202 and dgentime>=:dgentime and workno is not null
order by
    dgentime asc
""")

uploaded_audio_list = {}
clear_flag = False

while True:
    try:
        now = datetime.datetime.now()
        delta = datetime.timedelta(seconds=60*30)
        select_result = cc_conn.execute(
            sql,
            dgentime= now - delta
        )
        audio_list = list(select_result)
        for i in audio_list:
            if i.length and i.filename not in uploaded_audio_list:
                mobile = i.callid if i.callid not in invalid_mobiles \
                    else i.caller
                location = i.location
                location = '/'.join(location.split('\\')[2:])
                audio_path = 'http://192.168.1.207:8080/Record/' + \
                    location + '.wav'

                audio_file_name = audio_path.split('/')[-1]
                tmp_audio_response = requests.get(audio_path)
                with open('tmp_audio.wav', 'w') as f:
                    f.write(tmp_audio_response.content)

                # 上传录音
                record_datetime = str(i.dgentime).replace(' ','_')
                upload_audio_url = BASE_UPLOAD_AUDIO_URL.format(
                    mobile=mobile,
                    record_datetime=record_datetime,
                )
                upload_files = {
                    'upload_file': (
                        audio_file_name, open('tmp_audio.wav', 'rb'))
                }
                r = requests.post(upload_audio_url, files=upload_files)
                print r.text
                uploaded_audio_list[i.filename] = 1

    except Exception as e:
        print e

    current_hour = datetime.datetime.now().hour
    if (current_hour >= 23) and not clear_flag:
        uploaded_audio_list = {}
        clear_flag = True
    if current_hour == 1:
        clear_flag = False

    print len(uploaded_audio_list)
    time.sleep(10)
    print "run at: %s" % datetime.datetime.now()




